package server

import (
	"encoding/json"
	"fmt"
	"myLive/contact"
	"net"
	"time"
)

const (
	defaultPort = "11111"
	defaultIp   = "127.0.0.1"
)

var (
	members = make(map[net.Conn]bool)
	ln      net.Listener
	err     error

	//hasMember = make(chan bool, 1)
)

func detectUserAlive() {
	for {
		//if len(members) == 0 {
		//	hasMember <- false
		//}

		for member, _ := range members {
			m := contact.Message{Type: "AliveTest", Content: "ok"}
			buf, _ := json.Marshal(m)

			if _, err := member.Write(buf); err != nil {
				fmt.Printf("The guy[%v] has gone.\n", member.RemoteAddr())
				delete(members, member)
			}
		}
		time.Sleep(time.Second)
	}
}

func handleJoinLiveReq() {
	for {
		if conn, err := ln.Accept(); err != nil {
			fmt.Println("Accept Failed, ", err)
			return
		} else {
			members[conn] = true
			fmt.Printf("A guy[%v] has joined.\n", conn.RemoteAddr())

			buf, _ := json.Marshal(contact.Message{Type: "ConnReq", Content: "ok"})
			_, _ = conn.Write(buf)
		}

		//if len(members) == 1 {
		//	<-hasMember
		//}
	}
}

func dispatchMessage() {

	for i := 1; i < 10000; i++ {
		m := contact.Message{Type: "Data", Content: fmt.Sprintf("This is a vaild Msg--%d", i)}

		buf, _ := json.Marshal(m)

		for member, _ := range members {
			_, _ = member.Write(buf)
		}
		time.Sleep(time.Second)
	}

}

func OpenMyLive() {
	ln, err = net.Listen("tcp", defaultIp+":"+defaultPort)
	if err != nil {
		fmt.Println("Listen Failed, ", err)
		return
	}

	go handleJoinLiveReq()

	go detectUserAlive()

	//go dispatchMessage()

	time.Sleep(100 * time.Hour)
}
